//
//  LoginVC.m
//  DataStatistics
//
//  Created by Kang on 15/12/24.
//  Copyright © 2015年 YTYangK. All rights reserved.
//

#import "LoginVC.h"
#import "ACUserLoginManage.h"
#import "ACCustomTextFieid.h"
#import "MBProgressHUD+MJ.h"
#import <IQKeyboardManager.h>
#import "ACMainViewController.h"
#import "NetRequestClass.h"
#import "GetiPhoneDevice.h"
#import "UtilToolsClass.h"
#import "JPUSHService.h"
#import "UITextField+LolitaText.h"

#import "ACCustomAlertView.h"
@interface LoginVC ()<UITextFieldDelegate>{
    /** 初始化位置*/
    CGRect frameDefault;
    /** 判断是否点击了 */
    BOOL   isClick;
}

@end

@implementation LoginVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.phoneNum.delegate = self;
    self.password.delegate = self;
      [self converCurrentLanuage];
    /** text设置 */
    [self setTextFunction];
    /** 按钮设置 */
    [self setChoiceBoxFunction];
    if(![[ACUserLoginManage shareInstance].userCode isEqualToString:@""] || ![ACUserLoginManage shareInstance].userCode){
        //  已有账号
        self.phoneNum.text = [ACUserLoginManage shareInstance].userCode;//jeary
        self.password.text = [ACUserLoginManage shareInstance].userPassword;
        self.loginBtn.enabled = YES;
       
    }else{
        self.loginBtn.enabled = NO;
    }
  
}


- (void) unBindAccountForPush{
    // 设置推送别名
    [JPUSHService setAlias:@"" callbackSelector:@selector(tagsAliasCallback:tags:alias:) object:self];
}

- (void)tagsAliasCallback:(int)iResCode tags:(NSSet*)tags alias:(NSString*)alias {
    NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, tags , alias);
    if(!iResCode){
        // 成功
          NSLog(@"设备解绑成功");
     }else{ // 不成功
        NSLog(@"解绑失败,重新解绑");
        [self unBindAccountForPush];
    }
 
}

#pragma make  语言转换
- (void) converCurrentLanuage{
    [self.loginBtn setTitle:NSLocalizedString(@"登录",nil) forState:UIControlStateNormal];
    [self.loginBtn setTitle:NSLocalizedString(@"登录", nil) forState:UIControlStateDisabled];
    [self.reclsTeredBtn setTitle:NSLocalizedString(@"注册", nil) forState:UIControlStateNormal];
    [self.forcetPasswordBtn setTitle:NSLocalizedString(@"忘记密码", nil) forState:UIControlStateNormal];
}


#pragma mark 输入框文本的设置
- (void)setTextFunction{
    frameDefault = self.view.frame;
    _signStr = @"";
    [self.phoneNum addYTYanKTextFielStyle1:self.phoneNum withString:NSLocalizedString(@"手机号码",@"")];
    [self.phoneNum addTarget:self action:@selector(LVCtextLengthMethod:) forControlEvents:UIControlEventEditingChanged];
    self.password.secureTextEntry       =  YES; //密码类型
    self.password.clearsOnBeginEditing = NO;
    self.password.returnKeyType         = UIReturnKeySend;
    [self.password addYTYanKTextFielStyle1:self.password withString:NSLocalizedString(@"密码",@"")];
    
    [self.password addTarget:self action:@selector(LVCtextLengthMethod:) forControlEvents:UIControlEventEditingChanged];
    
//    [self rememberAction];
}


/** 按钮设置 */
- (void)setChoiceBoxFunction {
    [self.reclsTeredBtn addTarget:self action:@selector(ChoiceBoxAction:) forControlEvents:UIControlEventTouchDown];
    [self.forcetPasswordBtn addTarget:self action:@selector(ChoiceBoxAction:) forControlEvents:UIControlEventTouchDown];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    /** 设置状态栏为白色 */
//    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
   
    
    /*    解绑设备，在多人登陆同一个账号的时候，会给回调到此界面，因此需要解绑  */
    [self unBindAccountForPush];
    // 取消登陆标示
    [ACUserLoginManage shareInstance].loginTag = @"0";
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    UITapGestureRecognizer *tapGetstureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
    [self.view addGestureRecognizer:tapGetstureRecognizer]; //将触摸事件添加到当前view
    [[IQKeyboardManager sharedManager] disableToolbarInViewControllerClass:[LoginVC class]];
}




/**
 *  触发输入框的回调。当输入值进行改变时就会检测
 *
 */
- (void)LVCtextLengthMethod:(UITextField *)textField {
    if (self.password.text.length > 0 && self.phoneNum.text.length > 0) {
        self.password.enablesReturnKeyAutomatically  = NO;
        self.loginBtn.enabled   = YES;
    }else {
        self.password.enablesReturnKeyAutomatically  = YES;
        self.loginBtn.enabled = NO;
    }
    
    if(textField.tag == 1 ){
        if (textField == self.phoneNum) {
            if (textField.text.length > 15) {
                textField.text = [textField.text substringToIndex:15];
            }
        }
    }
    else {
        if (textField == self.password) {
            if (textField.text.length > 12) {
                textField.text = [textField.text substringToIndex:12];
            }
        }
    }
}

//
///** 获取密码的方法*/
- (void)rememberAction {
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"isAutomaticLogin"]isEqualToString:@"YES"]) {
        _phoneNum.text = [[NSUserDefaults standardUserDefaults]objectForKey:@"userCode"];
        _password.text = [[NSUserDefaults standardUserDefaults]objectForKey:@"passwordText"];
    }else {
        _phoneNum.text = @"";
        _password.text = @"";
    }
}



- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    return YES;
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == _phoneNum) {
        [_password becomeFirstResponder];
    }else {
         [self resignRespondersForTextFields];
         [self loginBtnCiake:_loginBtn];
    }
    return  YES;
}


- (BOOL)resignRespondersForTextFields {
    if (isClick) {
        isClick = NO;
        if (SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"568.0") ){
            [UIView animateWithDuration:0.24 animations:^{
                [self.view setFrame:frameDefault];
            } completion:nil];
        }
        
        [_phoneNum resignFirstResponder];
        [_password resignFirstResponder];
    }
    return isClick;
}

/** 键盘显示  */
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    if (!isClick) {
        isClick = YES;
    }
  
    if (_phoneNum.isFirstResponder == true || _password.isFirstResponder == true) {
         CGRect newFrome = self.view.frame;
        if (SCREEN_HEIGHT == 480 ) {
            newFrome.origin.y = -2 * textField.frame.size.height - 40;
        } else if (SCREEN_HEIGHT == 568) {
            newFrome.origin.y =   -1 * textField.frame.size.height - 20;
        }
        [UIView animateWithDuration:0.24 animations:^{
            [self.view setFrame:newFrome];
        } completion:^(BOOL finished) {
            
        }];
    }
}
/** 键盘隐藏 */
- (void)keyboardHide:(UITapGestureRecognizer *)sender {
    [self.view endEditing:YES];
    if (sender.state == UIGestureRecognizerStateEnded) {
         [self resignRespondersForTextFields];
    }

}



#pragma mark  注册、忘记密码
- (void)ChoiceBoxAction:(UIButton *)btn {
     BOOL  isRe = [self resignRespondersForTextFields];
    if (isRe == NO) {
        if (btn.tag == 1004 ) {
            _signStr = @"Forget";
            [self performSegueWithIdentifier:@"pushRegister" sender:self];
        }
        if (btn.tag == 1003) {
            _signStr = @"Registered";
            [self performSegueWithIdentifier:@"pushRegister" sender:self];
        }
    }
}

#pragma  mark   登陆方法
/**
 *  登录返回的信息可以用解归挡的形式保存LoginModel，可以采用偏好设置的方式保存，这里采用的偏好设置ACUserManager
 *
 */
- (IBAction)loginBtnCiake:(UIButton *)sender {
    [self.view endEditing:YES];
    __weak typeof (self)weakSelf = self;
    [[UtilToolsClass getUtilTools] addDoLoading];
    NSDictionary * param = @{@"isPhone":@(1),@"loginName":self.phoneNum.text,@"password":self.password.text};
    [NetRequestClass requestWithUrlForLoginIn:self andUrl:[REQUESTHEADER stringByAppendingString:@"login/loginSubmit.asp"] andParam:param success:^(ACUserLoginManage *model) {
        [[UtilToolsClass getUtilTools] removeDoLoading];
        if (model) {
            // 保存密码
             [ACUserLoginManage shareInstance].loginTag = @"1";
            [ACUserLoginManage shareInstance].userCode = _phoneNum.text;
            [ACUserLoginManage shareInstance].userPassword = _password.text;
            [UD synchronize];
            [weakSelf showMainViewController:model];
        }
    } failure:^(NSString *error) {
        [[UtilToolsClass getUtilTools] removeDoLoading];
        [UtilToolsClass addDisapperAlert:@"" withMessage:error];
    }];
    
}



- (void) showMainViewController:(ACUserLoginManage *)model{
    UIStoryboard * mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    ACMainViewController * mainViewController = [mainStory instantiateViewControllerWithIdentifier:@"mainViewController"];
    ACApplicationKeyWindow.rootViewController = mainViewController;
  
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier compare:@"pushRegister"] == NO) {
        id vc = segue.destinationViewController;
        [vc setValue:_signStr forKey:@"RAVCsignStr"];
    }
}

@end
